/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.weed.net;


import com.weed.core.WeedException;
import com.weed.net.listener.CallbackListener;
import com.weed.net.listener.SourceEvent;
import com.weed.net.listener.SourceListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 默认的实现者。
 * @author Jason
 */
public class DefaultSource implements ISource {
    
    
    protected SourceFactory sourceFactory ;
        /**存储所有的事件.*/
    protected ArrayList<SourceListener> events = new ArrayList<SourceListener>();
    /**cache*/
    protected HashMap cache = new HashMap();
    /**
     * config.
     */
    protected HashMap config = new HashMap();
     
    public boolean submit(Object obj,CallbackListener listener) throws WeedException {
        if(obj == null ){
           throw new WeedException("发送的对象不能为空！");
        }
        IRequest request = getRequest();
        if(request==null)
           throw new WeedException("请求处理者不能为空！");
        try{
            request.write(obj, listener);
            return true;
        }catch(Exception ex){
            throw new WeedException(ex);
        }
    }

    public void addSourceListener(SourceListener listener) {
        events.add(listener);
    }

    public boolean removeSourceListener(SourceListener listener){
        return events.remove(listener);
    }

    public SourceFactory getSourceFactory() {
        return sourceFactory;
    }

    public void init(SourceFactory sourceFactory,HashMap config) {
        this.sourceFactory = sourceFactory;
        this.config = config;
    }
    
   
    public IRequest getRequest() {
        try {
           Class source = Class.forName((String)getConfig().get(SourceFactory.REQUEST_INTERFACE_IMPL));
           IRequest request = (IRequest)source.newInstance();
           request.init(this);
           return request;
        } catch (InstantiationException ex) {
            Logger.getLogger(DefaultSource.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(DefaultSource.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DefaultSource.class.getName()).log(Level.SEVERE, null, ex);
        } 
        return null;
   }
    
   public void processEvent(SourceEvent event) throws WeedException {
        int size = events.size();
        for (int i = 0; i < size; i++) {
            try {
               SourceListener listener = events.get(i);
               listener.listener(event);
            } catch (Exception ex) {
                throw new WeedException(ex);
            }
        }
    }

   public HashMap getCache() {
        return cache;
    }

    public HashMap getConfig() {
        return config;
    }
 
}
